'use strict';

module.exports = (option, app) => {
  return async function(ctx, next) {
    try {
      await next();
    } catch (err) {
      // 生产环境时 500 错误的详细错误内容不返回给客户端，因为可能包含敏感信息
      let { code = 'Error', message = 'Error', status = 500 } = err;
      app.emit(status === 500 ? 'error' : 'warn', err, this);
      message = status === 500 && app.config.env === 'prod' ? 'Internal Server Error' : err.message;

      if (typeof code === 'number') {
        code = 'InternalError';
        message = 'The request processing has failed due to some unknown error, exception or failure.';
      }

      ctx.body = {
        code,
        message,
      };
      if (status === 422) {
        ctx.body.detail = err.errors;
      }
      ctx.status = status;
    }
  };
};
